package com.cyy.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public ResData defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        String path = req.getRequestURI();
        if(e instanceof CommonException){
            CommonException ce = (CommonException) e;
            return ResData.error(ce.getCode(),ce.getMsg());
        }
        if(e instanceof MissingServletRequestParameterException){
            MissingServletRequestParameterException ex = (MissingServletRequestParameterException)e;
            return ResData.error(ResData.FAIL,"参数错误："+ex.getMessage());
        }
        if(e instanceof MethodArgumentTypeMismatchException){
            MethodArgumentTypeMismatchException ex = (MethodArgumentTypeMismatchException)e;
            return ResData.error(ResData.FAIL,"参数类型转换错误："+ex.getMessage());
        }
        LOGGER.error("error path :" + path, e);
        return ResData.error("未知错误");
    }
}
